package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 套餐 前端控制器
 * </p>
 *
 * @author violet
 * @since 2022-04-22 03:32:22
 */
@Slf4j
@RestController
@RequestMapping("/setmeal")
@Api(tags = "套餐相关接口")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 套餐分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @ApiOperation("套餐分页查询")
    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = true),
            @ApiImplicitParam(name = "name", value = "套餐名称", required = false),
    })
    public R<Page> page(int page, int pageSize, String name) {
        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();
        //构造条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper();
        //添加排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        queryWrapper.like(name != null, Setmeal::getName, name);
        //执行查询
        setmealService.page(pageInfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, setmealDtoPage, "records");

        List<Setmeal> records = pageInfo.getRecords();

        //重新改造records
        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);

            Long categoryId = item.getCategoryId();//分类id
            Category category = categoryService.getById(categoryId); //根据id拿到分类对象
            if (category != null) {
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(list);
        return R.success(setmealDtoPage);
    }

    /**
     * 起售
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/1")
    public R<String> Start_sale(@RequestParam("ids") List<Long> ids) {
        for (Long id : ids) {
            Setmeal setmeal = setmealService.getById(id);
            setmeal.setStatus(1);
            setmealService.updateById(setmeal);
        }
        return R.success("成功修改菜品状态");
    }

    /**
     * 停售
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/0")
    public R<String> halt_sales(@RequestParam("ids") List<Long> ids) {
        for (Long id : ids) {
            Setmeal setmeal = setmealService.getById(id);
            setmeal.setStatus(0);
            setmealService.updateById(setmeal);
        }
        return R.success("成功修改菜品状态");
    }

    /**
     * 根据id查询套餐的信息 用于数据的回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.getByIdWithDishs(id);
        if (setmealDto != null) {
            LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(SetmealDish::getSetmealId, id);
            List<SetmealDish> setmealDishList = setmealDishService.list(queryWrapper);
            setmealDto.setSetmealDishes(setmealDishList);
            return R.success(setmealDto);
        }
        return R.error("没有查询到对应套餐的信息");
    }

    /**
     * 修改套餐信息
     *
     * @param setmealDto
     * @return
     */
    @PutMapping()
    @CacheEvict(value = "SetmealDtoCache", allEntries = true) //删除该分类下的所有缓存数据
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        setmealService.updateWithDishes(setmealDto);
        return R.success("修改套餐成功");
    }

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "SetmealDtoCache", allEntries = true) //删除该分类下的所有缓存数据
    @ApiOperation("新增套餐接口")
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        setmealService.saveWithDishes(setmealDto);
        return R.success("新增套餐成功");
    }

    /**
     * 批量删除套餐(在setmeal里面)和套餐对应的菜品(在setmealDish里面)
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @Transactional
    @CacheEvict(value = "SetmealDtoCache", allEntries = true) //删除该分类下的所有缓存数据
    public R<String> delete(@RequestParam("ids") List<Long> ids) {
        //查询套餐状态,如果为起售状态,则不能删除,抛出异常
        //select count(*) from setmeal where id in (1,2,3) and status = 1
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId, ids);
        queryWrapper.eq(Setmeal::getStatus, 1);
        int count = (int) setmealService.count(queryWrapper);
        if (count > 0) {
            throw new CustomException("套餐正在售卖中,不能删除");
        }
        setmealService.removeByIds(ids);
        //删除关系表中数据----setmeal_dish
        //delete from setmeal_dish where setmeal_id in (1,2,3)
//        for (Long id : ids) {
//            LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
//            queryWrapper1.eq(SetmealDish::getSetmealId,id);
//            setmealDishService.remove(queryWrapper1);
//        }
        //效果一样
        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(queryWrapper1);

        return R.success("删除套餐成功");
    }

    @GetMapping("/list")
    @Cacheable(value = "SetmealDtoCache", key = "#setmealDto.categoryId+'_'+#setmealDto.status")
    public R<List<SetmealDto>> list(SetmealDto setmealDto) {
        log.info(setmealDto.toString());
        //拿到该套餐分类下面所有的套餐
        LambdaQueryWrapper<Setmeal> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Setmeal::getCategoryId, setmealDto.getCategoryId());
        queryWrapper1.eq(Setmeal::getStatus, 1);
        queryWrapper1.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(queryWrapper1);


        List<SetmealDto> setmealDtoList = list.stream().map((item) -> {
            SetmealDto setmealDto1 = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto1);
            //获取当前套餐的id
            Long setMealId = item.getId();
            //根据套餐id 拿到 该套餐下面的所有菜品
            LambdaQueryWrapper<SetmealDish> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(SetmealDish::getSetmealId, setMealId);
            List<SetmealDish> setmealDishList = setmealDishService.list(queryWrapper2);
            setmealDto1.setSetmealDishes(setmealDishList);
            return setmealDto1;
        }).collect(Collectors.toList());

        return R.success(setmealDtoList);
    }

    @GetMapping("/dish/{id}")
    public R<List<SetmealDishDto>> getSetmealDishById(@PathVariable Long id) {
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishList = setmealDishService.list(queryWrapper);
        List<SetmealDishDto> dishlist = setmealDishList.stream().map((item) -> {
            SetmealDishDto setmealDishDto = new SetmealDishDto();
            BeanUtils.copyProperties(item, setmealDishDto);

            Dish dish = dishService.getById(item.getDishId());
            setmealDishDto.setImage(dish.getImage());

            return setmealDishDto;
        }).collect(Collectors.toList());

        return R.success(dishlist);
    }
}

